<!--
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2022-12-07 14:34:34
 * @LastEditors: Andy
 * @LastEditTime: 2023-04-04 14:30:50
-->
<template>
  <el-form
    :model="loginForm"
    label-position="top"
    :hide-required-asterisk="true"
    ref="ruleFormRef"
    :rules="rules"
    label-width="0px"
    @submit.native.prevent
  >
    <el-form-item label="" prop="userName">
      <el-input
        v-model="loginForm.userName"
        auto-complete="off"
        :placeholder="$t('login.userNamePlaceholder')"
        type="text"
        @keyup.enter.native="onSubmit()"
      />
    </el-form-item>
    <el-form-item label="" prop="password">
      <el-input
        v-model="loginForm.password"
        auto-complete="off"
        :placeholder="$t('login.passwordPlaceholder')"
        type="password"
        @keyup.enter.native="onSubmit()"
      />
    </el-form-item>
    <el-form-item label="" prop="code">
      <x-code-input
        ref="codeInput"
        v-model="loginForm.code"
        @refreshCode="getAuthCodeImg"
        :code-url="identifyCode"
        :placeholder="$t('login.codePlaceholder')"
        @keyup.enter.native="onSubmit()"
      />
    </el-form-item>
    <div class="flex-row flex-between" style="margin-bottom: 16px">
      <el-checkbox v-model="loginForm.rememberMe">
        {{ $t('login.remerberMe') }}
      </el-checkbox>
      <!-- <el-link type="primary" :underline="false" @click="handleRegister">{{ $t('login.registerAccount') }}</el-link> -->

      <el-link type="primary" :underline="false" @click="handleForget">{{ $t('login.forgetPwd') }}</el-link>
    </div>

    <el-form-item label-width="76px">
      <el-button type="primary" :loading="loading" size="medium" style="width: 100%" @click.prevent="onSubmit()">
        {{ $t('login.loginBtnLabel') }}
      </el-button>
    </el-form-item>
    <div class="tip">
      <span type="default" :underline="false">{{ $t('login.hanNoAccount') }}</span>
      <el-link type="primary" :underline="false" @click="handleRegister">{{ $t('login.registerNow') }}</el-link>
    </div>
  </el-form>
</template>
<script>
  import { encrypt, throttle } from '@package/utils'
  import { TokenService } from '@package/service'
  import login from '../pinia/login.js'
  import { apiGetImage } from '../api'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    data() {
      return {
        login,
        loginForm: {
          userName: '',
          password: '',
          code: '',
          rememberMe: false,
          captchaKey: ''
        },
        loading: false,
        rules: {
          userName: [{ required: true, trigger: 'blur', message: '请输入用户名' }],
          password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
          code: [
            { required: true, trigger: 'change', message: '请输入验证码' }
            // { validator: this.checkPictureCode, trigger: 'blur' }
          ]
        },
        identifyCode: ''
      }
    },
    watch: {
      'loginForm.userName': {
        handler(userName) {
          if (!userName) {
            this.loginForm.password = ''
          }
        },
        immediate: true
      }
    },
    created() {
      this.getAuthCodeImg()
      this.loginForm.rememberMe = TokenService.getToken('remember') || false
      if (this.loginForm.rememberMe) {
        this.loginForm.rememberMe = JSON.parse(this.loginForm.rememberMe)
        this.loginForm.userName = TokenService.getToken('username') || ''
        this.loginForm.password = TokenService.getToken('password') || ''
      }
    },
    methods: {
      getAuthCodeImg() {
        apiGetImage().then(({ data }) => {
          this.identifyCode = data.captcha
          this.loginForm.captchaKey = data.captchaKey
        })
      },
      checkPictureCode(rule, value, callback) {
        if (value == this.loginForm.code) {
          return callback()
        }
        this.getAuthCodeImg()
        callback(new Error('验证码错误'))
      },
      // 注册账号
      handleRegister() {
        this.$router.push({ path: '/register' })
      },
      handleForget() {
        this.$router.push({ path: '/forgetPwd' })
      },
      /**
       * @param loginForm - 登录表单数据
       * 用户登录
       */
      onSubmit: throttle(function () {
        this.loading = true
        const userLogin = login()
        this.$refs.ruleFormRef.validate((valid) => {
          if (valid) {
            if (this.loginForm.rememberMe) {
              TokenService.setExToken('username', this.loginForm.userName)
              TokenService.setExToken('password', this.loginForm.password, 30)
              TokenService.setExToken('remember', this.loginForm.rememberMe, 30)
            }
            const formData = new FormData()
            formData.append('username', this.loginForm.userName)
            formData.append('password', encrypt(this.loginForm.password))
            formData.append('grant_type', 'password')
            formData.append('scope', 'message.read message.write')
            formData.append('captcha', this.loginForm.code)
            formData.append('captchaKey', this.loginForm.captchaKey)
            this.loading = true
            userLogin.LoginIn(formData).then(
              () => {
                // this.loading = false
                this.$emit('handleLoginSucess')
              },
              () => {
                this.getAuthCodeImg()
                this.loading = false
              }
            )
          } else {
            this.getAuthCodeImg()
            this.loading = false
          }
        })
      }, 1000)
    }
  }
</script>
<style lang="scss" scoped>
  .code-img {
    display: inline;
    margin-left: 16px;
  }
  .tip {
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
